#include "todoparser.h"

#include <QTextStream>
#include <QFile>

#include <QStringList>

TodoParser::TodoParser(TodoManager &manager, QObject *parent) :
    QObject(parent), _manager(manager)
{

}

bool TodoParser::parseFile(QString fileName)
{
    QFile f(fileName);
    if( !f.open(QIODevice::ReadOnly | QIODevice::Text) ) {
        return false;
    }

    QTextStream ts(&f);
    while(!ts.atEnd()) {
        QString line = ts.readLine();
        TodoItemPtr item = parseLine(line);
        if( !item.isNull() )
            _manager.addTodo(item);
    }

    f.close();

    return true;

}

void TodoParser::parseText(QString data)
{

    QTextStream ts(&data);
    while(!ts.atEnd()) {
        QString line = ts.readLine();
        TodoItemPtr item = parseLine(line);
        if( !item.isNull() )
            _manager.addTodo(item);
    }

}

TodoItemPtr TodoParser::parseLine(QString line)
{
    line = line.trimmed();
    if( line.isEmpty() ) return TodoItemPtr();

    //QStringList list = line.split( QChar((char)29) );
    QStringList list = line.split( QChar('|') );
    for(int i=list.size(); i < TodoItem::propCount(); i++) {
        list.push_back("");
    }

    TodoItemPtr item( new TodoItem(list[0], list[1], list[2], list[3], list[4], list[5]) );
    return item;
}

QString TodoParser::_generateLine(TodoItemPtr item)
{

    QStringList list;
    //QString code, QString priority, QString description, QString urgent, QString date, QString complete
    list << QString::number(item->code) << QString::number(item->priority) << item->description << (item->urgent?"S":"N") << item->date.toString("yyyy-MM-dd") << (item->complete?"S":"N");

    return list.join('|');

}

bool TodoParser::saveFile(QString fileName)
{
    QFile f(fileName);
    if( !f.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text) ) {
        return false;
    }

    QTextStream ts(&f);
    TodoManager::TodoMap todoMap = _manager.getTodoMap();
    for(TodoItemPtr item : todoMap) {
        ts << _generateLine(item) << '\n';
    }

    ts.flush();
    f.close();

    return true;
}

